#Cell line

#library packages
library(ggplot2)
library(data.table)

library(dplyr)

library(optparse)

option_list <- list(
  make_option("--i", default = "", type = "character", help = "input file"),
  make_option("--c", default = "", type = "character", help = "color file"),
  make_option("--order", default = "", type = "character", help = "order by"),
  make_option("--l", default = "", type = "character", help = "log"),
  make_option("--o", default = "", type = "character", help = "output png file")
)
opt <- parse_args(OptionParser(option_list = option_list))

#import source data
expr<-fread(opt$i) %>%
              as.data.frame()
rownames(expr)<-expr[,1]
gene <- expr$gene
expr<-expr[,-1]
mypal<-read.table(opt$c)[,1] %>%
                as.character()

#dim parameters and extract corresponding statitstics
order<-opt$order
logscale<-opt$l
expr.gene<-data.frame(cell = colnames(expr),expr = as.numeric(expr[gene,]),
                      log2expr = log2(as.numeric(expr[gene,])+1)) #修改
if ( order == 'alphabet'){
  expr.gene$cell<-factor(expr.gene$cell,levels = expr.gene$cell)
} else if (order == 'expression'){
  expr.gene<-arrange(expr.gene,desc(expr))
  expr.gene$cell<-factor(expr.gene$cell,levels = expr.gene$cell)
}

#plot #修改
png(file=opt$o,width=3000,height=1200,res=300)
if ( logscale == 'Yes') {
  ggplot(expr.gene)+geom_col(aes(x=cell,y=log2expr,fill=cell),color='black')+
    scale_fill_manual(values = mypal)+
    theme_bw()+theme(legend.position = 'none')+labs(y='Log2(TPM+1)',x='Cell line',title = gene)+
    theme(axis.text.x = element_text(angle=45,hjust = 1,vjust = 1,face = 'bold'),plot.title = element_text(hjust = 0.5),
          axis.title.x = element_blank(),axis.title.y = element_text(face = 'bold'),
          plot.margin = unit(c(0,0,0,1),'cm') )#+
    #scale_y_continuous(labels = function(x)format(x,scientific = F,digits = 0))
} else {
  ggplot(expr.gene)+geom_col(aes(x=cell,y=expr,fill=cell),color='black')+
    scale_fill_manual(values = mypal)+
    theme_bw()+theme(legend.position = 'none')+labs(y='TPM',x='Cell line',title = gene)+
    theme(axis.text.x = element_text(angle=45,hjust = 1,vjust = 1,face = 'bold'),plot.title = element_text(hjust = 0.5),
          axis.title.x = element_blank(),axis.title.y = element_text(face = 'bold'),
          plot.margin = unit(c(0,0,0,1),'lines'))#+
    #scale_y_continuous(labels = function(x)format(x,scientific = F,digits = 0))
}
dev.off()

#export csv
colnames(expr.gene)[1]<-'cell_line'
write.csv(expr.gene,paste('gene.csv',sep = ''),row.names = F)
